package 树;

import 抽象数据类型.TreeNode;

import static 剑指offer.ThreeOrderTraverse.backOrder;
import static 剑指offer.ThreeOrderTraverse.preOrder;


/**
 * @description:
 * @author: ywk
 * @date: 2020-12-17
 */
public class 前序遍历和中序遍历的结果还原一棵二叉树 {
    public static TreeNode buildTree(int[] preorder, int preStart, int preEnd,
                                     int[] inorder, int inStart, int inEnd) {
        if (preStart > preEnd || inStart > inEnd) return null;
        TreeNode<Integer> root = new TreeNode(preorder[preStart]);
        int inRoot = findIndex(inorder, root.val, inStart, inEnd);
        System.out.println(root.val);
        int numsLeft = inRoot - inStart;
        root.left = buildTree(preorder, preStart + 1, preStart + numsLeft, inorder, inStart, inRoot - 1);
        root.right = buildTree(preorder, preStart + numsLeft + 1, preEnd, inorder, inRoot + 1, inEnd);
        return root;
    }

    public static int findIndex(int[] arr, int tar, int start, int end) {
        for (int i = start; i <= end; i++) {
            if (arr[i] == tar) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] xianxu = {1, 2, 4, 5, 6, 3};
        int[] zhongxu = {5, 4, 6, 2, 1, 3};
        int[] houxu = {5, 6, 4, 2, 3, 1};
        TreeNode treeNode = buildTree(xianxu, 0, xianxu.length - 1, zhongxu, 0, zhongxu.length - 1);
        System.out.println(preOrder(treeNode));
        System.out.println(backOrder(treeNode));
    }
}
